package com.add;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.StaticLog;
import com.add.domain.Clock;
import com.add.domain.MorningClock;
import com.add.domain.NoonClock;
import com.add.domain.User;

import java.util.Date;
import java.util.List;

public class Main1 {
    //private static final Logger logger = LoggerFactory.getLogger(Main1.class);
    //private static final File userFile;
    private static final String userFileStr;
    public static List<User> users;

    static {
        //初始化配置文件
        ClassPathResource resource = new ClassPathResource("data.json");
        //userFile = new File(resource.getAbsolutePath());
        userFileStr = resource.readUtf8Str();
        //解析所有用户
        loadUsers();
    }

    //加载所有打卡用户
    static void loadUsers() {
        try {
            //加载配置文件
            String usersStr = JSONUtil.parseObj(userFileStr).getStr("users");
            JSONArray arr = JSONUtil.parseArray(usersStr);
            users = arr.toList(User.class);
        } catch (Exception e) {
            //文件加载异常日志
            StaticLog.error("json文件加载异常");
        }
    }
    //单个打卡
    public static void clickOne(int id,Clock morningClock,Clock noonClock){
        User u=users.get(id);
        StaticLog.info("{}开始打卡", u.getName());
        boolean ok = false;
        ok = morningClock.clock(u);
        //ok = noonClock.clock(u);
        if (ok) {
            StaticLog.info("{}打卡完成", u.getName());
        } else {
            StaticLog.info("{}打卡失败", u.getName());
        }
    }

    public static void main(String[] args) {
        if (users == null) return;
        //获取打卡对象
        Clock morningClock = new MorningClock();
        Clock noonClock = new NoonClock();
        //获取当前时间
        Date now = DateUtil.date();
        StaticLog.info(now + "开始打卡-----------------------------------------------------------------------");
        //全部打卡
        for (User user : users) {
            StaticLog.info("{}开始打卡", user.getName());
            boolean ok = !(user.getMorningClick()&& user.getNoonClick());
            if (user.getMorningClick() && morningClock.validTime(now))
                ok = morningClock.clock(user);
            if (user.getNoonClick() && noonClock.validTime(now))
                ok = noonClock.clock(user);
            if (ok) {
                StaticLog.info("{}打卡完成", user.getName());
            } else {
                StaticLog.info("{}打卡失败", user.getName());
            }
        }
        //clickOne(1,morningClock,noonClock);
        now = DateUtil.date();
        StaticLog.info(now + "打卡结束-----------------------------------------------------------------------");
    }
}